﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ModuleITDesk.DAL;
using ModuleITDesk.DAL.Model;
using ModuleITDesk.BLL;
using System.Threading;
namespace ModuleITDesk
{
    public partial class CRMain : Form
    {
        BLLUsers userBLL = new BLLUsers();
        DALUser UserDAL = new DALUser();
        DALProject ProjectDAL = new DALProject();
        BLLProject ProjectBLL = new BLLProject();
        int UserID = -1;
        int userIDLogin = -1;
        int projectID = -1;
        ModuleITDeskEntities contextDB;
        public CRMain()
        {
            InitializeComponent();
            contextDB = new ModuleITDeskEntities();
        }
        private void btnTimeSheet_Click(object sender, EventArgs e)
        {
            groupBoxLogin.Visible = true;
            groupBoxRegister.Visible = groupBoxProject.Visible = groupBoxChangedPassword.Visible = false;
        }
        private void Login()
        {
            if (txtusernameLogin.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Username is required", "Message");
            }
            else if (txtpasswordLogin.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Password is required", "Message");
            }
            else
            {
                CheckLoginDto checkedLogin = new CheckLoginDto();
                DALCheckedLogin checkedLoginAPI = new DALCheckedLogin();
                checkedLogin = checkedLoginAPI.CheckedLogin(txtusernameLogin.Text.Trim(), txtpasswordLogin.Text.Trim());
                if (!checkedLogin.IsSuccess)
                {
                    MessageBox.Show(checkedLogin.Message, "Message");
                    return;
                }
                if(checkedLogin.IsSuccess && checkedLogin.Permission==0)
                {
                    //MessageBox.Show(checkedLogin.Message, "Message");
                    txtusernameinfo.Text = checkedLogin.Username;
                    txtfirstnameinfo.Text = checkedLogin.FirstName;
                    txtlastnameinfo.Text = checkedLogin.LastName;
                    txtUserNameChangedPassword.Text = checkedLogin.Username;
                    txtOldPassword.Text = checkedLogin.Password;
                    userIDLogin = checkedLogin.UserId;
                    groupBoxLogin.Visible = false;
                    groupBoxProject.Visible = true;
                    groupBoxProject.Dock = DockStyle.Fill;
                    LoadProjectList(userIDLogin);
                    return;                    
                }
                if (checkedLogin.IsSuccess && checkedLogin.Permission == 1)
                {
                    this.Visible = false;
                    CRAdmin cradmin = new CRAdmin(checkedLogin.UserId,checkedLogin.Username,checkedLogin.Password);
                    cradmin.Show();
                }
                //this.Hide();
            }
        }
        private void CRMain_Load(object sender, EventArgs e)
        {
            this.Visible = true;
            groupBoxLogin.Visible = false;
            groupBoxRegister.Visible = false;
            groupBoxProject.Visible = false;
            groupBoxChangedPassword.Visible = false;
            dgvproject.AutoGenerateColumns = false;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            groupBoxLogin.Visible = false;
            groupBoxRegister.Visible = true;
            groupBoxRegister.Dock = DockStyle.Left;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void txtnotnow_Click(object sender, EventArgs e)
        {
            groupBoxLogin.Visible = true;
            groupBoxRegister.Visible = false;
        }
        private void Register()
        {
            if (string.IsNullOrEmpty(txtUserNameSignUp.Text) || string.IsNullOrEmpty(txtPasswordSignUp.Text) || string.IsNullOrEmpty(txtFirstnameSignUp.Text) || string.IsNullOrEmpty(txtLastNameSignUp.Text) || string.IsNullOrEmpty(txtEmailSignUp.Text) || string.IsNullOrEmpty(cbowhichoneSignUp.Text))
            {
                MessageBox.Show("Information Required", "Warning");
            }
            else
            {
                if (txtPasswordSignUp.Text != txtconfirmpasswordSignUp.Text)
                {
                    MessageBox.Show("Confirm password not match", "Warning");
                }
                try
                {
                    User Users = new User();
                    Users.UserID = UserID;
                    Users.UserName = txtUserNameSignUp.Text;
                    Users.Password = txtPasswordSignUp.Text;
                    Users.FirstName = txtFirstnameSignUp.Text;
                    Users.LastName = txtLastNameSignUp.Text;
                    Users.Email = txtEmailSignUp.Text;
                    Users.WhichOne = cbowhichoneSignUp.Text;
                    Users.Permission = 0;
                    if (userBLL.InserUser(Users))
                    {
                        MessageBox.Show("Sign in successfull", "Warning");
                        groupBoxLogin.Visible = true;
                        groupBoxRegister.Visible = false;
                    }
                    else
                    {
                        MessageBox.Show("Username is duplicated, Please try again", "Warning");                         
                        groupBoxLogin.Visible = false;
                        groupBoxRegister.Visible = true;
                    }
                    
                   
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Sign in fail, Please try again", "Warning");
                }
            }
        }
        private void txtsignup_Click(object sender, EventArgs e)
        {
            Register();            
        }

        private void btnChangedPassword_Click(object sender, EventArgs e)
        {
            groupBoxChangedPassword.Visible = true;
            groupBoxLogin.Visible = false;
            groupBoxRegister.Visible = false;
            groupBoxChangedPassword.Dock = DockStyle.Left;
            groupBoxProject.Visible = false;
        }
        // Changed Password
        private void btnCancelChanged_Click(object sender, EventArgs e)
        {
            txtUserNameChangedPassword.Text = "";
            txtOldPassword.Text = "";
            txtNewPassword.Text = "";
        }
        private void ChangedPassword()
        {
            if (userBLL.ChangedPassword(txtUserNameChangedPassword.Text, txtOldPassword.Text, txtNewPassword.Text))
            {
                MessageBox.Show("Password changed successfull", "Warning");
                groupBoxChangedPassword.Visible = false;
                groupBoxLogin.Visible = true;
                groupBoxLogin.Dock = DockStyle.Left;
            }
            else
            {
                MessageBox.Show("Password changed fail, Try again", "Warning");
            }

        }

        private void btnSubmitChanged_Click(object sender, EventArgs e)
        {
            ChangedPassword();
        }
        
        private void btnSignOut_Click(object sender, EventArgs e)
        {
            groupBoxLogin.Visible = true;
            groupBoxRegister.Visible = false;
            groupBoxProject.Visible = false;
            groupBoxChangedPassword.Visible = false;
        }
        private void LoadProjectList(int iduser)
        {
            try
            {
                dgvproject.Rows.Clear();
                //var list = ProjectBLL.GetProjectListByUserID(iduser);
                var list = from p in contextDB.Projects
                           from u in contextDB.Users
                           where p.UserID == iduser && u.UserID==p.UserID
                           select new
                           {
                               projectid = p.ProjectID,
                               projectname = p.ProjectName,
                               createddate = p.CreatedDate,
                               customername = p.CustomerName,
                               activity = p.Activity,
                               hours = p.Hours,
                               percent = p.PercentToFinish,
                               billable = p.Billable,
                               whichinsolex = p.WhichInsolex,
                               cost = p.Cost,
                               username = u.UserName,
                               userid = u.UserID,
                               useremail = u.Email,
                               userfirstname = u.FirstName,
                               userlastname = u.LastName
                           };
                if (list.ToList() != null)
                {
                    foreach (var item in list)
                    {
                        dgvproject.Rows.Add(item.projectid, item.username, item.createddate.ToString("MM/dd/yyyy"), item.customername, item.projectname, item.activity, item.billable, item.hours, item.percent);
                    }
                    dgvproject.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        //Area process about Project
        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtcostumername.Text) || string.IsNullOrEmpty(txtprojectname.Text) || string.IsNullOrEmpty(txtactivity.Text) || string.IsNullOrEmpty(txthours.Text) || string.IsNullOrEmpty(txtpercent.Text) || string.IsNullOrEmpty(cbobillable.Text) || string.IsNullOrEmpty(cbowhichinsolex.Text))
            {
                MessageBox.Show("Information required", "Warning");
            }
            else if (int.Parse(txtpercent.Text) > 100)
            {
                MessageBox.Show("Percent cannot larger 100", "Warning");
                txtpercent.Focus();
            }            
            else
            {
                Project Projects = new Project();
                Projects.ProjectID = projectID;
                Projects.UserID = userIDLogin;
                Projects.CustomerName = txtcostumername.Text;
                Projects.ProjectName = txtprojectname.Text;
                Projects.Activity = txtactivity.Text;
                Projects.Billable = cbobillable.Text;
                Projects.Hours = int.Parse(txthours.Text);
                Projects.PercentToFinish = int.Parse(txtpercent.Text);
                Projects.WhichInsolex = cbowhichinsolex.Text;
                Projects.CreatedDate = DateTime.Parse(dateTimePickerchoose.Text);
                Projects.Cost = 10.0;
                if (ProjectBLL.InsertProject(Projects))
                {
                    //MessageBox.Show("Insert successful", "Warning");                   
                }
                else
                {
                    MessageBox.Show("Insert fail", "Warning"); 
                }
                LoadProjectList(userIDLogin); 
            }
        }
        private void txthours_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtpercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        
        //Update status in progressbar
        private void UpdateProgressBar(int i)
        {
            if (progressBar1.InvokeRequired)
            {
                progressBar1.Invoke(new Action<int>(UpdateProgressBar), new Object[] { i });
            }
            else
            {
                Thread.Sleep(200);
                progressBar1.Refresh();
                progressBar1.Value = i;
                progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
                                                      (float)10.25, FontStyle.Bold),
                                                      Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
            }
        } 
        private void dgvproject_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = dgvproject.CurrentCell.RowIndex;
            txtprojectID.Text = dgvproject.Rows[rowindex].Cells["colID"].Value.ToString();
            txtcostumername.Text = dgvproject.Rows[rowindex].Cells["colCustomer"].Value.ToString();
            txtprojectname.Text = dgvproject.Rows[rowindex].Cells["colProject"].Value.ToString();
            txtpercent.Text = dgvproject.Rows[rowindex].Cells["colPercent"].Value.ToString();
            txtactivity.Text = dgvproject.Rows[rowindex].Cells["colTask"].Value.ToString();
            txthours.Text = dgvproject.Rows[rowindex].Cells["colHours"].Value.ToString();
            cbobillable.Text = dgvproject.Rows[rowindex].Cells["colBillable"].Value.ToString();
            lblviewdatechoose.Text = dgvproject.Rows[rowindex].Cells["colDate"].Value.ToString();
            progressBar1.Value = int.Parse(dgvproject.Rows[rowindex].Cells["colPercent"].Value.ToString());
            int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
            using (Graphics gr = progressBar1.CreateGraphics())
            {
                gr.DrawString(percent.ToString() + "%",
        SystemFonts.DefaultFont,
        Brushes.Black,
        new PointF(progressBar1.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
            SystemFonts.DefaultFont).Width / 2.0F),
        progressBar1.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
            SystemFonts.DefaultFont).Height / 2.0F)));
            }
            

          
                
        }

        private void btnTotalHours_Click(object sender, EventArgs e)
        {
            DateTime datefrom=dateTimePickerFrom.Value.Date;
            DateTime dateto=dateTimePickerTo.Value.Date;
            try
            {
                var sql = from project in contextDB.Projects
                          where project.UserID == userIDLogin
                          && project.CreatedDate.Day >= datefrom.Day
                          && project.CreatedDate.Month >= datefrom.Month
                          && project.CreatedDate.Day <= dateto.Day
                          && project.CreatedDate.Month <= dateto.Month
                          select new 
                          {
                              hours=project.Hours
                          };
                if (sql != null)
                {
                    foreach(var l in sql.ToList())
                    {
                        var totalhour = sql.Select(p => p.hours).Sum();
                        txtcaltotalhours.Text = totalhour.ToString();
                    }
                }
            }
            catch(Exception ex)
            {  }
        }

        private void txtpasswordLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Login();
            }
        }
    }
}
